package com.example.ee.aidl;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Process;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

public class RemoteService extends Service {
    final String TAG = "RemoteService";

    private RemoteBinder binder = new RemoteBinder();
    private RemoteCallbackList<ICallback>  callbackList = new RemoteCallbackList<>();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    class RemoteBinder extends IRemoteService.Stub{

        void callback(){
            int count = callbackList.beginBroadcast();
            try {
                for (int i = 0; i < count; i++) {
                    callbackList.getBroadcastItem(i).fun2();
                }
            } catch (RemoteException e) {
                Log.e(TAG, e.getMessage());
            } finally {
            }
            callbackList.finishBroadcast();
        }


        @Override
        public int getPid() throws RemoteException {
            return Process.myPid();
        }

        @Override
        public void fun1() throws RemoteException {
            Log.d(TAG, "fun1 in remote service ");
            callback();
        }

        @Override
        public void registerCallback(ICallback cb) throws RemoteException {
            callbackList.register(cb);
        }

        @Override
        public void unregisterCallback(ICallback cb) throws RemoteException {
            callbackList.unregister(cb);
        }
    }
}
